package com.skymxc.demo.explorer.util;

import android.content.Context;
import android.os.Environment;
import android.text.format.Formatter;
import android.util.Log;

import com.skymxc.demo.explorer.R;
import com.skymxc.demo.explorer.core.FileType;
import com.skymxc.demo.explorer.core.SortType;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import static android.content.ContentValues.TAG;

/**
 * Created by sky-mxc
 */

public class FileUtil {


    /**
     * 获取目录下的子文件集合
     * @param parent 目录
     * @param showHideFile 是否显示隐藏文件
     * @param sort 排序方式
     * @return 子文件集合
     */
    public static List<File> loadAllChildren(File parent, final boolean showHideFile, SortType sort){
        File[] files = parent.listFiles(new FilenameFilter() {
            /**
             * 允许
             * @param dir 文件
             * @param name 名字
             * @return
             */
            @Override
            public boolean accept(File dir, String name) {
                if (showHideFile) return true;

                // 以“ . ” 开头 说明是隐藏文件
                if (name.startsWith(".")) return false;

                return true;
            }
        });

        //排序
        Comparator<File> comparator =null;

        switch (sort){
            case NAME:
                comparator = nameComparator;
                break;
            case DATE:
                comparator = dateComparator;
                break;
            case FILETYPE:
                comparator = fileTypeComparator;
                break;
            case SIZE:
                comparator = sizeComparator;
                break;
        }

        if (comparator!=null) {
            //根据比较器排序
            Arrays.sort(files, comparator);
        }
        return Arrays.asList(files);
    }

    //名字比较
    private static Comparator<File> nameComparator = new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            //忽略文件大小写比较
            return o1.getName().compareToIgnoreCase(o2.getName());
        }
    };

    //日期比较
    private static Comparator<File> dateComparator = new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            //获取最后修改时间
            long time1=o1.lastModified();
            long time2 = o2.lastModified();
            long difference= time1-time2;
            if (difference>Integer.MIN_VALUE && difference<= Integer.MAX_VALUE){
                return (int) difference;
            }
            //转到分钟
            return (int) (difference/1000/60);
        }
    };

    //尺寸比较
    private static Comparator<File> sizeComparator = new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {


            if (o1.isDirectory() && o2.isDirectory()){      //文件夹 按照文件名排列
                return o1.getName().compareToIgnoreCase(o2.getName());
            }else if(o1.isFile() && o2.isFile()){            //都是文件
                long difference = o1.length()-o2.length();
                if (difference>Integer.MIN_VALUE && difference<= Integer.MAX_VALUE){
                    return (int) difference;
                }
                return  difference< 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }else{               //一个文件 一个文件夹
                if (o1.isDirectory()){  //如果是文件夹 就在上
                    return Integer.MIN_VALUE;
                }else{
                    return  Integer.MAX_VALUE;
                }

            }


        }
    };
    //文件类型比较
    private static Comparator<File> fileTypeComparator = new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {

            if ((o1.isDirectory() && o2.isDirectory()||(o1.isFile() && o2.isFile()))){      //同为目录或者文件 按照名称排序
                return o1.getName().compareToIgnoreCase(o2.getName());
            }else{      //一个文件 一个文件夹 文件夹在上
                if (o1.isDirectory()){
                    return Integer.MIN_VALUE;
                }else{
                    return  Integer.MAX_VALUE;
                }

            }


        }
    };


    /**
     * 获取文件图标
     * @param file
     * @return
     */
    public static int getIcon(File file) {
        FileType type = FileType.parseFile(file);
        switch (type){
            case UNKNOW:
                return R.mipmap.unknown;
            case DIR:
                return R.mipmap.folder_yellow;
            case AUDIO:
                return  R.mipmap.music;
            case DATABASE:
                return R.mipmap.database;
            case EXL:
                return R.mipmap.excel;
            case IMAGE:
                return R.mipmap.image;
            case PDF:
                return  R.mipmap.pdf;
            case PPT:
                return R.mipmap.powerpoint;
            case PSD:
                return  R.mipmap.psd;
            case TEXT:
                return R.mipmap.text;
            case VIDEO:
                return R.mipmap.video;
            case WORD:
                return R.mipmap.word;
            case ZIP:
                return R.mipmap.archive_yellow;
        }

        return  R.mipmap.unknown;
    }

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");

    /**
     * 获取文件信息
     * 最后修改日期
     * 大小
     * @param context
     * @param file
     * @return
     */
    public static String getFileInfo(Context context,File file) {
       long time= file.lastModified();

        StringBuffer sb = new StringBuffer();
        sb.append(sdf.format(new Date(time)));
        if (file.isFile()){
            sb.append("\t"+ Formatter.formatFileSize(context,file.length()));
        }

        return  sb.toString();
    }

    /**
     * 获取SDCard 的信息
     * @param context
     * @return
     */
    public static String getSDCardInfo(Context context){
        File file = Environment.getExternalStorageDirectory();
        long total = file.getTotalSpace();
        long usable = file.getUsableSpace();
        //读写权限
        String  r_w = (file.canRead()?"r/":"-/")+(file.canWrite()?"w":"-");
       return String.format("%s  已用, %s 可用, %s ",Formatter.formatFileSize(context,total-usable),Formatter.formatFileSize(context,usable),r_w);

    }

    /**
     * 获取文件详细信息
     * @param context
     * @param file
     * @return
     */
    public static String getDetailFileInfo(Context context, File file) {
        StringBuffer sb = new StringBuffer("");
        sb.append("名称："+file.getName());
        sb.append("\n大小："+Formatter.formatFileSize(context,getFileSize(file)));
        sb.append("\n最后修改时间"+sdf.format(new Date(file.lastModified())));
        sb.append("\n路径："+file.getPath());
        if (file.isFile()){

            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                //获取mdf5实例
                MessageDigest md = MessageDigest.getInstance("MD5");
                //获取文件摘要
                md.update(fis.getChannel().map(FileChannel.MapMode.READ_ONLY,0,file.length()));
                //摘要字节码
                byte[] b = md.digest();
                //转为 16禁止
                String md5 = new BigInteger(1,b).toString(16);
                sb.append("\nmd5:"+md5);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }else{

        }
        Log.i(TAG,"===getDetailFileInfo= :"+sb.toString());
        return  sb.toString();
    }

    /**
     * 获取文件或者文件夹大小
     * @param file
     * @return
     */
    public static long  getFileSize(File file){

        if (file.isFile()){
            return file.length();
        }else{
            long size =0;
            for (File f :file.listFiles()){
                size+=getFileSize(f);
            }
            return size;
        }
    }


    /**
     * 获取文件数量(包含子文件)
     * @param file
     * @return
     */
    public static int getDescendantCount(File file){
        int count =0;
        if (file.isDirectory()){
            File [] files = file.listFiles();
            if (files.length >0){
                for (File f:files){
                    count+=getDescendantCount(f);
                }
            }

        }
        count++;
        return count;
    }

    /**
     * copy 文件
     * @param file
     * @param moveFile
     * @return
     */
    public static boolean copyFile(File file, File moveFile) {
        FileInputStream fis =null;
        FileOutputStream fos =null;
        try {
            if(moveFile.createNewFile()){
              fis = new FileInputStream(file);
                fos = new FileOutputStream(moveFile);

                int len=-1;
                byte[] b = new byte[1024];
                while ((len=fis.read(b))!=-1){
                    fos.write(b,0,len);
                }
            }


        } catch (IOException e) {
            e.printStackTrace();
            if (moveFile.exists()){
                moveFile.delete();
            }
            Log.e(TAG,"==copy file "+moveFile.getName()+" 失败");
        }finally {

                try {
                    if (fis !=null){
                      fis.close();
                    }
                    if (fos != null){
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

        }

        return true;
    }
}
